const { HTTP } = require('./utils/http');
const { api } = require('./utils/api');
const { request } = new HTTP();
import Event from './utils/event.js'
//挂载到wx对象上
wx.event=new Event();

// app.js
App({
  onLaunch() {
    const token = wx.getStorageSync('token');
    this.globalData.isLogin =  token ? true : false;   
    if (token == '') {
      this._wxLogin();
    } else {
      this._getUserInfo();
    }
  },
  _wxLogin() {
    const self = this;
    wx.login({
      success: function (res) {
        const code = res.code;
        if (code) {
          self._authorization(code);
        }
      }
    });
  },

  // 判断用户是否注册
  async _authorization(code) {
    const {returnCode = '', bean } = await request({
      url: api.authorization,
      method: 'post',
      data: { code }
    });
    if (returnCode === '0000') {
      wx.setStorageSync('token', bean);
      this.globalData.isLogin = false;
      this._getUserInfo();
      let timer = setTimeout(() => {
        this.loginCallBack();
        clearTimeout(timer);
        timer = null;
      }, 200);
    }
    if (returnCode == 807) {
      this.globalData.isLogin = true;
      this.globalData.openid = bean;
      let timer = setTimeout(() => {
        this.loginCallBack();
        clearTimeout(timer);
        timer = null;
      }, 200);
    }
  },

  async _getUserInfo() {
    const {returnCode = '', returnMessage = '', bean = {}} = await request({
      url: api.getUser,
      method: 'get',
      data: {}
    });

    if (returnCode === '0000') {
      this.globalData.isLogin = false;
      this.globalData.userInfo = bean.user;
      let timer = setTimeout(() => {
        this.userInfoCallBack && this.userInfoCallBack();
        clearTimeout(timer);
        timer = null;
      }, 500);
    }
    if (returnCode == '10006' && returnMessage == '禁止访问') {
      wx.clearStorage();
      this.globalData.isLogin = true;
      this._wxLogin();
    }
  },

  globalData: {
    isLogin: false,
    userInfo: null,
    selectPhoto: null,
    code: null,
    appid: '',
    openid: '',
    phoneNumber: '' 
  }
})

